package com.ttcaca.cas.android.client.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    public HttpURLConnection sendRequest(String url,String param,String cookie) throws Exception {

        byte[] entitydata = param.getBytes();

        HttpURLConnection c = (HttpURLConnection) new URL(url)
                .openConnection();

        if(!"".equals(cookie)){
            c.setRequestProperty("Cookie", cookie);
        }

        c.setInstanceFollowRedirects(false);

        c.setRequestMethod("POST");

        c.setDoOutput(true);

        c.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        c.setRequestProperty("Content-Length",
                String.valueOf(entitydata.length));

        OutputStream outStream = c.getOutputStream();
        outStream.write(entitydata);
        outStream.flush();
        outStream.close();

        int responeCode = -1;

        responeCode = c.getResponseCode();

        if(responeCode == 500){
            throw new Exception("CAS服务端异常");
        }

        return c;
    }

    public HttpURLConnection sendRequest1(String url) throws Exception {

        HttpURLConnection c = (HttpURLConnection) new URL(url)
                .openConnection();

        c.setInstanceFollowRedirects(false);

        c.setRequestMethod("GET");

        return c;
    }

    public String getResponse(HttpURLConnection c) throws IOException {

        String sCurrentLine = "";

        String sTotalString = "";

        java.io.InputStream is = c.getInputStream();

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is));
        while ((sCurrentLine = reader.readLine()) != null)
            if (sCurrentLine.length() > 0)
                sTotalString = sTotalString + sCurrentLine.trim();

        return sTotalString;
    }

}
